<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@ page isELIgnored="false" %> 
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

String articleId = request.getParameter("atclid");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

	<head>
		<meta charset="UTF-8">
		<title><c:out value="${pageTitle }">OoM-编辑文章</c:out></title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<link rel="icon" href="/static/img/logo.ico" type="image/x-icon" />
	
		<link href="/static/css/base.css" rel="stylesheet" />
		<link href="/static/css/index.css" rel="stylesheet" />
		<link href="/static/css/m.css" rel="stylesheet" />
		
		<link href="/static/plugin/bootstrap/css/bootstrap.min.css" rel="stylesheet">
		<script src="/static/plugin/jquery.min.js"></script>
		<link href="/static/plugin/highlight/styles/dracula.css" rel="stylesheet">
		<script src="/static/plugin/highlight/highlight.pack.js"></script>
		<script src="/static/plugin/showdown-master/dist/showdown.min.js"></script>

		<!-- 上传图片 -->
		<link href="/static/plugin/bootstrap/fileinput/cropper.min.css" rel="stylesheet">
		<link href="/static/plugin/bootstrap/fileinput/sitelogo.css" rel="stylesheet">
		<script src="/static/plugin/bootstrap/fileinput/cropper.min.js"></script>
		<script src="/static/plugin/bootstrap/fileinput/sitelogo.js"></script>
		<script src="/static/plugin/bootstrap/js/bootstrap.min.js"></script>
		<script src="/static/js/publish_marked.js"></script>
	
		<script type="text/javascript">
		   var IMAGE_RATE = 16 / 9;
			window.onload = function() {
				var oH2 = document.getElementsByTagName("h2")[0];
				var oUl = document.getElementsByTagName("ul")[0];
				if(oH2) {
					oH2.onclick = function() {
						var style = oUl.style;
						style.display = style.display == "block" ? "none" : "block";
						oH2.className = style.display == "block" ? "open" : "";
					}
				}
			};
			
			function afterUploadImage(resp) {
				console.log(resp);
				if(resp && resp.success && resp.data) {
					var url = resp.data.imageFullUrl;
					console.log(url);
					
					appendImageToText(url);
				}
				
			}
			
			function appendImageToText(url) {
				url = url || 'https://www.oomabc.com/static/img/logo_nav.png';
				
				insertImg(url);

				convert();
			}
		</script>
		<style type="text/css">
		body {
			overflow-x : hidden;
		}
		.topnav ul {
			margin : 0px;
		}
		#markdownInput {
			outline : none;
			resize : none;
			padding : 10px;
			height : 596px;
			width : 100%;
			border : 1px solid #EEEEEE;
		}
		body{
			background-color : #F7F7F7;
			color : black !important;
			font-size : 15px !important;
		}
		
		table.blogArticleSetting{
			border-collapse : collapse;
		}
		.blogArticleSettingTd{
			line-height : 50px;
		}
		input::-webkit-input-placeholder {
			/* placeholder颜色  */
			color: #aab2bd;
			/* placeholder字体大小  */
			font-size: 12px;
			/* placeholder位置  */
			text-align: left;
		}
		input.inputStyle1{
			padding : 10px;
			outline : none;
			border : none;
			font-size : 30px;
		}
		input[type="radio"]{
			vertical-align: middle; 
			margin-top: -2px; 
			margin-bottom: 1px;
		}
		
		div.tagInputDiv{
			float : left;
			margin-right : 15px;
			cursor : pointer;
			font-size : 15px;
			border : 1px solid #EEEEEE;
			padding-left : 4px;
			padding-right : 4px;
			border-radius : 3px;
		}
		blockquote{
			font-size : 14px;
		}
		.h1, .h2, .h3, .h4, .h5, .h6, h1, h2, h3, h4, h5, h6{
			font-weight : bold !important;
		}
		
		div.toolsBarSpan{
		  float : left;
		  padding : 5px;
		  cursor : pointer;
		  margin : 5px;
		  border-radius : 3px;
		}
        div.toolsBarSpan:hover{
            background-color : #DDDDDD;
        }
        div#codeList{
            box-shadow: 0px 0px 3px rgba(88, 88, 88, 0.56); transition: all .2s ease-out;
            background-color : white;
            display : none;
        }
        div.codeList_item{
            padding-left : 20px;
            padding-right : 20px;
            cursor : pointer;
            line-height : 32px;
        }
        div.codeList_item:hover{
            background-color : #EFEFEF;
        }
        div.codeList_item:nth-child(n + 2){
            border-top : 1px solid #EDEDED;
        }
        div.toolsBarSpanSep{
            float : left; 
            border-left : 1px solid #DCDCDC; 
            margin-top : 8px;
            margin-left : 5px;
        }
		</style>
	</head>
	<body>
		<header>
			<div class="tophead">
				<div class="logo">
					<a href="/home"><img src="/static/img/logo_nav.png" width="225" height="50" /></a>
				</div>
				<nav class="topnav" id="topnav">
					<ul>
						<li><a href="index" >管理首页</a></li>
						<li><a href="publish" id="topnav_current">发布文章</a></li>
					</ul>
				</nav>
			</div>
		</header>
	    <div class="header-blank">
	    </div>
	
        <div id="codeList" style="position : absolute; padding-top : 10px; padding-bottom :10px;">
        </div>
        
		<!-- 图片上传 -->
		<div>
			<div class="modal fade" id="avatar-modal" aria-hidden="true" aria-labelledby="avatar-modal-label" role="dialog" tabindex="-1">
				<div class="modal-dialog modal-lg">
					<div class="modal-content" style="
                        margin-top: 121px;
					">
						<form class="avatar-form" action="uploadImage" enctype="multipart/form-data" method="post">
							<div class="modal-header">
								<button class="close" data-dismiss="modal" type="button">&times;</button>
								<h4 class="modal-title" id="avatar-modal-label">上传图片</h4>
							</div>
							<div class="modal-body">
								<div class="avatar-body">
									<div class="avatar-upload">
										<input class="avatar-src" name="avatar_src" type="hidden">
										<input class="avatar-data" name="avatar_data" type="hidden">
										<label for="avatarInput">图片上传</label>
										<input class="avatar-input" id="avatarInput" name="avatarfile" type="file"></div>
									<div class="row">
										<div class="col-md-9">
											<div class="avatar-wrapper"></div>
										</div>
										<div class="col-md-3">
											<div class="avatar-preview preview-lg"></div>
											<div class="avatar-preview preview-md"></div>
											<div class="avatar-preview preview-sm"></div>
										</div>
									</div>
									<div class="row avatar-btns">
										<div class="col-md-9">
											<div class="btn-group">
												<button class="btn" data-method="rotate" data-option="-90" type="button" title="Rotate -90 degrees"><i class="fa fa-undo"></i> 向左旋转</button>
											</div>
											<div class="btn-group">
												<button class="btn" data-method="rotate" data-option="90" type="button" title="Rotate 90 degrees"><i class="fa fa-repeat"></i> 向右旋转</button>
											</div>
										</div>
										<div class="col-md-3">
											<button class="btn btn-success btn-block avatar-save" type="submit"><i class="fa fa-save"></i> 保存修改</button>
										</div>
									</div>
								</div>
							</div>
			  			</form>
			  		</div>
				</div>
			</div>
			
			<div class="loading" aria-label="Loading" role="img" tabindex="-1"></div>
		</div>
		<!-- 图片上传 -->
		
        <img src="/static/img/upimage.png" id="hiddenImg" style="display : none;" width="20" height="20" />

		<form action="publishblog" method="post" id="blogForm">
		<div class="w_container">
			<div class="container" style="width : 100%; " >
				<input type="hidden" name="articleId" />
				<div style="width : 1300px; margin : 20px auto 0px auto; background-color : white; padding : 10px;
				box-shadow: 0px 0px 8px rgba(88, 88, 88, 0.36); transition: all .2s ease-out;">
					<table style="width : 100%;">
						<tr>
							<td valign="top" >
								<div id="MarkdownPreview" style="padding : 10px; width : 610px; height : 700px; 
								border-right : 1px solid #EEEEEE; overflow : auto;
								">
								</div>
							</td>
							<td valign="top">
								<div style="width : 670px; height : 700px; padding-left : 10px; 
								">
									<div>
										<input name="articleTitle" style="width : 650px;" type="text" placeholder="请输入标题" class="inputStyle1" value="" />
									</div>
									<!-- 工具栏 -->
									<div style="padding-top : 1px;">
										<div style="border : 1px solid #EEEEEE; border-bottom : none; padding : 1px;
										
										">
                                            <div class="toolsBarSpan" onclick="insert_fontWeightBold();" title="粗体">
                                                <img src="/static/img/cuti.png" width="16" height="16" />
                                            </div>
                                            <div class="toolsBarSpan" onclick="insert_slanting();" title="斜体">
                                                <img src="/static/img/xieti.png" width="16" height="16" />
                                            </div>
                                            
                                            <div class="toolsBarSpanSep">&nbsp;</div>
                                            <div class="toolsBarSpan" onclick="insert_rank_list();" title="有序列表" >
                                                <img src="/static/img/rank_list.png" width="16" height="16" />
                                            </div>
                                            <div class="toolsBarSpan" onclick="insert_list();" title="无序列表">
                                                <img src="/static/img/unrank_list.png" width="16" height="16" />
                                            </div>
                                            <div class="toolsBarSpan" onclick="insert_midLine();" title="分割线">
                                                <img src="/static/img/mid_line.png" width="16" height="16" />
                                            </div>
                                            <div class="toolsBarSpan" onclick="insert_lineEnter();" title="换行">
                                                <img src="/static/img/line_enter.png" width="16" height="16" />
                                            </div>
                                            
                                            <div class="toolsBarSpanSep">&nbsp;</div>
                                            <div class="toolsBarSpan" " onclick="showLinkBlock();" title="超链接 " >
                                                <img src="/static/img/alink.png" width="18" height="16" />
                                            </div>
                                            <div class="toolsBarSpan" id="crop-avatar" title="上传图片 " >
                                                <a class="avatar-view1" href="javascript:void(0);" >
                                                    <img src="/static/img/upimage.png" width="18" height="16" />
                                                </a>
                                            </div>
                                            <div class="toolsBarSpan" onclick="insert_codeBlock();" title="行内代码块">
                                                <img src="/static/img/simple_code.png" width="18" height="18"/>
                                            </div>
                                            <div class="toolsBarSpan" onclick="showInsertCodeBlock(this);" title="代码块（多语言风格）">
                                                <img src="/static/img/full_code.png" width="18" height="18" />
                                            </div>
											<div style="clear : both;"></div>
										</div>
										<textarea id="markdownInput" name="articleContent" rows="" cols="" onkeyup="convert();" ></textarea>
									</div>
								</div>
							</td>
						</tr>
					</table>
				</div>
				
				<div style="width : 1300px; margin : 20px auto 120px auto; background-color : white; padding : 30px;
				padding-left : 50px; padding-right : 50px;
				box-shadow: 0px 0px 8px rgba(88, 88, 88, 0.36); transition: all .2s ease-out;">
					<div class="titleLine">
						博客设置
					</div>
					<table class="blogArticleSetting">
						<tr>
							<td class="blogArticleSettingTd" style="padding-right : 100px;"><span class="fieldMust">*</span>博客分类</td>
							<td>
								<div class="_selected" id="blogTypeSelect" forName="categoryId">
									<div class="_selected_title" sWidth="200" >请选择</div>
									<div class="_selected_list">
										<ul class="list-group">
											<li class="list-group-item" value="1">技术-工程化应用</li>
											<li class="list-group-item" value="2">技术-技术学习/探索</li>
											<li class="list-group-item" value="4">技术-自娱自乐</li>
											<li class="list-group-item" value="3">生活-随便写写</li>
											<li class="list-group-item" value="5">娱乐/放松/其他</li>
										</ul>
									</div>
								</div>
							</td>
						</tr>
						<tr>
							<td class="blogArticleSettingTd"><span class="fieldMust">*</span>来源</td>
							<td>
								<div>
									<label><input type="radio" name="srcType" value="1" /> 原创</label>&nbsp;&nbsp;&nbsp;
									<label><input type="radio" name="srcType" value="2" /> 转载</label>
								</div>
							</td>
						</tr>
						<tr>
							<td class="blogArticleSettingTd" valign="top"><span class="fieldMust">*</span>标签</td>
							<td valign="top">
								<div>
									<input type="text" name="" placeholder="输入关键字，回车确认" class="inputStyle2" id="inputTagId" />
									<span class="spanInfo">标签最多输入8个</span>
								</div>
								<div id="tagsDiv" style="padding-top : 10px; padding-bottom : 30px;">
								</div>
								<div style="clear : both;"></div>
							</td>
						</tr>
						<tr>
							<td class="blogArticleSettingTd"><span class="fieldMust">*</span>推荐等级</td>
							<td>
								<div>
									<input onkeyup="value=value.replace(/[^\d]/g,'')" placeholder="数字" type="text" name="priority" style="width : 80px;" class="inputStyle2" />
									<span class="spanInfo">用于标记文章的推荐优先级，数字，值越大优先级越高</span>
								</div>
							</td>
						</tr>
					</table>
					
                    <div class="titleLine" style="line-height : 40px;">&nbsp;</div>
	                <div style="padding : 20px; padding-left : 20px;">
	                    <input type="button" value="发布文章" class="btnStyle1" onclick="publishBlog();" />
	                </div>
				</div>
			</div>
		</div>
<!-- 
		<div style="background-color : white; width :100%; height : 80px; position : fixed; bottom : 0px; 
		box-shadow: 3px 1px 11px rgba(0, 0, 0, 0.26); transition: all .2s ease-out; z-index : 99999; 
		">
			<div style="padding : 20px; padding-left : 100px;">
				<input type="button" value="发布文章" class="btnStyle1" onclick="publishBlog();" />
			</div>
		</div> -->
		</form>
		
		
		<div class="alert alert-warning" style="display :none ; position : fixed; width : auto;" id="messageDiv">
			<div class="msg_div" style="width : 400px;">
				<strong>警告！</strong>您的网络连接有问题。
			</div>
		</div>
		
	</body>
	
	
	<script type="text/javascript">
	
	hljs.initHighlightingOnLoad();
	
	var converter = new showdown.Converter({extensions: function() {
		  function htmlunencode(text) {
		    return (
		      text
		        .replace(/&amp;/g, '&')
		        .replace(/&lt;/g, '<')
		        .replace(/&gt;/g, '>')
		      );
		  }
		  return [
		    {
		      type: 'output',
		      filter: function (text, converter, options) {
		        // use new shodown's regexp engine to conditionally parse codeblocks
		        var left  = '<pre><code\\b[^>]*>',
		            right = '</code></pre>',
		            flags = 'g',
		            replacement = function (wholeMatch, match, left, right) {
		              // unescape match to prevent double escaping
		              match = htmlunencode(match);
		              return left + hljs.highlightAuto(match).value + right;
		            };
		        return showdown.helper.replaceRecursiveRegExp(text, replacement, left, right, flags);
		      }
		    }
		  ];
	}()});
	
	function convert(){
	    var text = document.getElementById("markdownInput").value;
	    
	    var html = converter.makeHtml(text);

	    document.getElementById("MarkdownPreview").innerHTML = html;

		$('pre code').each(function(i, block) {
		    hljs.highlightBlock(block);
		});
		
		//$('#MarkdownPreview').scrollTop(9999999);
	}
	
	$(function() {
		$('#markdownInput').keydown(function(e) {
			if(e.keyCode===9){
			    var position=this.selectionStart+4;//此处我用了两个空格表示缩进，其实无所谓几个，只要和下面保持一致就好了。
			    this.value=this.value.substr(0,this.selectionStart)+'    '+this.value.substr(this.selectionStart);
			    this.selectionStart=position;
			    this.selectionEnd=position;
			    this.focus();
			    console.log(this.value);
			    e.preventDefault();
			} 
		});

		initSelect();
		
		var currentArticleId = '<%=articleId%>';
		var hiddenIdInput = $('input[name="articleId"]');
		hiddenIdInput.val("");
		if(currentArticleId && currentArticleId.length > 10) {
			jQuery.ajax({
				url : 'detail?atclid=' + currentArticleId,
				type : 'get',
				success : function(article) {

					if(article != null) {
						hiddenIdInput.val(currentArticleId);
						
						$('input[name="articleTitle"]').val(article.articleTitle);
						$('#markdownInput').val(article.articleContent);

						showClickItemValue($('#blogTypeSelect').find('li.list-group-item[value="' + article.categoryId + '"]'));
						
						$('input[type="radio"][name="srcType"][value="' + article.srcType + '"]').attr('checked', true);
						
						var tags = article.tags;
						if(tags) {
							for(var i in tags) {
								appendTag(tags[i]);
							}
							
						}
						
						$('input[name="priority"]').val(article.priority);
						
						//初始化样式
						convert();
					}
				}
			});
		}
		
		//初始化可选代码list
		var _hCode = '';
		for(var i in codeList) {
			var codeName = codeList[i];
			_hCode += '<div class="codeList_item" onclick="insert_codeM(\'' + codeName + '\');">' + codeName + '</div>';
		}
		var codeListObj = $('#codeList');
		codeListObj.html(_hCode);
		codeListObj.mouseout(function(e) {
		    var o = $(e.toElement);
		    if(o.attr('id') == 'codeList' || o.parent('div#codeList').length > 0) {
		    } else {
		    	codeListObj.fadeOut(0);
		    }
		});
	});
	
	function initSelect() {
		
		//初始化下拉列表 
		$('._selected').click(function() {
			var obj = $(this);
			if(obj.data('show')) {
				obj.find('._selected_list').fadeOut(0);
				obj.data('show', false);
			} else {
				obj.find('._selected_list').fadeIn(0);
				obj.data('show', true);
			}
		});
		$('._selected').mouseout(function(e) {
			var targetObj = $(e.target);
			if(targetObj.parents('._selected').length == 0) {
				var obj = $(this);
				obj.find('._selected_list').fadeOut(0);
				obj.data('show', false);
			}
		});
		$('._selected_list,._selected_title').mouseout(function(e) {
			var targetObj = $(e.toElement);
			if(targetObj.parents('._selected').length == 0) {
				var obj = $(this).parents('._selected');
				obj.find('._selected_list').fadeOut(0);
				obj.data('show', false);
			}
		});

		//点击 
		$('._selected_list').find('li.list-group-item').click(function() {
			showClickItemValue($(this));
		});
		
		$('._selected').each(function() {
			var thisObj = $(this);
			var thisTitle = thisObj.find('._selected_title');
			var w = thisTitle.attr('sWidth') - 0;

			thisTitle.css({
				width : w + 'px'
			});
			
			thisObj.find('li.list-group-item').css({
				width : w + 'px'
			});
			
			thisObj.append('<input type="hidden" value="" class="_select_value_input" name="' + thisObj.attr('forName') + '" />');
		});
		
		//blogTypeSelect
		
		//标签输入
		$('#inputTagId').keyup(function(e) {

			if(e.keyCode=== 13){
				var tag = $(this).val();
				console.log(tag);
				
				appendTag(tag);
				
				$(this).val('');
			}

		    e.preventDefault();
		});
	}
	
	function appendTag(tag){

		if($('#tagsDiv').find('input[value="' + tag + '"]').length > 0) {
			return;
		}
		
		$('#tagsDiv').append('<div class="tagInputDiv" onclick="deleteThisTag(this);"><span>' + tag
				+ '</span><input type="hidden" value="' + tag + '" name="tags" class="tagInput" /></div>');
	}
	
	//点击下拉列表，后续可以包装为方法
	function showClickItemValue(obj) {

		var parent = obj.parents('._selected');
		
		parent.find('._selected_title').html(obj.html());
		
		parent.data('selectValue',obj.attr('value'));
		
		parent.find('._select_value_input').val(obj.attr('value'));
	}
	
	function publishBlog() {
		//title
		var title = $('input[name="articleTitle"]').val();
		console.log(title);
		if(title == null || title.length < 5) {
			messageDiv('<strong>错误！</strong>博客标题为必填，长度为5~80！');
			return;
		}
		if(title.length > 80) {
			messageDiv('<strong>错误！</strong>博客标题为必填，长度为5~80！');
			return;
		}
		
		//content
		var content = $('#markdownInput').val();
		if(!content || content.length < 20 ) {
			messageDiv('<strong>错误！</strong>内容长度至少为20！');
			return;
		}
		
		//分类
		var blogType = $('#blogTypeSelect').data('selectValue');
		if(!blogType) {
			messageDiv('<strong>错误！</strong>请选择‘博客分类’！');
			return;
		}

		//src
		var src = $('input[type="radio"][name="srcType"]:checked').val();
		console.log(src);
		if(src === undefined) {
			messageDiv('<strong>错误！</strong>请选择来源 ！');
			return;
		}
		
		//tags
		var tagsLen = $('input[name="tags"]').length;
		if(tagsLen == 0) {
			messageDiv('<strong>错误！</strong>请输入标签！');
			return;
		}
		if(tagsLen > 8) {
			messageDiv('<strong>错误！</strong>标签个数不能超过8个，点击标签删除多余！');
			return;
		}
		
		//priority
		var priority = $('input[name="priority"]').val();
		console.log(priority);
		if(!priority) {
			messageDiv('<strong>错误！</strong>请输入推荐等级！');
			return;
		}

		//messageDiv('<strong>错误！</strong>这是提示信息！');
		$('#blogForm').submit();
	}
	function deleteThisTag(thisObj) {
		$(thisObj).remove();
	}
	
	function messageDiv(msg) {
		var obj = $('#messageDiv');
		obj.find('.msg_div').html(msg);
		var left = ($(document).width() - obj.width())/2;
		obj.css({
			position : 'fixed',
			//opacity : 1,
			left : left + 'px',
			top : '230px'
		});
		
		obj.stop(true).fadeIn(0, function() {
			obj.delay(2000).fadeOut(444);
		});
	}

	

	</script>

</html>